package com.exadel;

import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.Formatter;

/**
 * Created with IntelliJ IDEA.
 * User: alec
 * Date: 15.01.13
 * Time: 11:05
 * To change this template use File | Settings | File Templates.
 */
public class YouTubeParser implements YoutubeParseble {

    private ArrayList<ChildVideo> pages;
    private Connection connector;
    @Override
    public void parse(Connection htmldoc) {
        this.connector = htmldoc;
        Elements links = htmldoc.getDocument().getElementsByClass(RELATED_VIDEO);
        pages = new ArrayList<ChildVideo>();
        for(Element e : links)
        {
            ChildVideo page = new ChildVideo();
            page.setName(e.getElementsByClass(TITLE).text());
            page.setRating(e.getElementsByClass(VIEW_COUNT).text());
            page.setUrl(e.select(A).first().attr(REFERENCE));
            pages.add(page);
        }
    }

    @Override
    public void getToChild(int number) {
       String url = pages.get(number).getUrl();
       connector.connect(url);
        this.parse(connector);
        this.print();
    }

    @Override
    public void print() {
        Formatter frm ;
        int current = 0;
        System.out.println("___________________________________Name_________________________________________Rating______________________________Reference_______________");
        for(ChildVideo page:pages){
            frm = new Formatter();
            //If the name does not fit in the table, then use reduction
            if(page.getName().length()>64){
                frm.format("%3.3s|  %-64.64s...|  %-20.20s|  %-50.50s",++current
                        ,page.getName(),page.getRating(),page.getUrl());
            }
            else{
                frm.format("%3.3s|  %-64.64s   |  %-20.20s|  %-50.50s",++current
                        ,page.getName(),page.getRating(),page.getUrl());
            }
            System.out.println(frm);
            frm.close();
        }
    }
}
